package com.bustle.user;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;

import com.bustle.user.dto.authentication.AuthenticationDto;
import com.bustle.user.dto.authentication.AuthenticationDtoDao;
import com.bustle.user.dto.user.UserDto;
import com.bustle.user.dto.user.UserDtoDao;

@Local
public interface AuthenticationDtoManager
{
  public UserDto authenticate(String aLogin, String aPassword) throws AuthenticationException;
  public void createUser(UserDto aUser, String aLogin, String aPassword) throws AuthenticationException;

  public UserDto getUser(int anId);
  public void updateUser(UserDto aUser);

  @Stateless
  public class DefaultAuthenticationDtoManager implements AuthenticationDtoManager
  {
    @Override
    public UserDto authenticate(String aLogin, String aPassword) throws AuthenticationException
    {
      AuthenticationDto authentication = authenticationDtoDao.retrieve(aLogin);
      if (authentication == null)
      {
        throw new AuthenticationException("Unknown login " + aLogin);
      }
      if (!authentication.getPassword().equals(aPassword))
      {
        throw new AuthenticationException("Bad password for login " + aLogin);
      }
      return authentication.getUser();
    }

    @Override
    public void createUser(UserDto aUser, String aLogin, String aPassword) throws AuthenticationException
    {
      if (authenticationDtoDao.retrieve(aLogin) != null)
      {
        throw new AuthenticationException("Unable to create user " + aUser + " with existing login " + aLogin);
      }
      AuthenticationDto authentication = new AuthenticationDto();
      authentication.setLogin(aLogin);
      authentication.setPassword(aPassword);
      authentication.setUser(aUser);
      authenticationDtoDao.create(authentication);
    }

    @Override
    public UserDto getUser(int anId)
    {
      return userDtoDao.retrieve(anId);
    }

    @Override
    public void updateUser(UserDto aUser)
    {
      userDtoDao.update(aUser);
    }

    @EJB
    protected AuthenticationDtoDao authenticationDtoDao;
    @EJB
    protected UserDtoDao userDtoDao;
  }
}
